#include "fstream"
#include "iostream"
#include "vector"
#include "algorithm"
#include "numeric"
#include "filesystem"
#include "list"
#include "string"
#include "array"
#include "map"
using namespace std;
namespace  fs = std::filesystem;

vector<fs::path> directories = {"../18","../20","../22","../46","../48","../50","../52","../54","../60","../70","../80"};

void readFile(vector<double> & vec,int pos)
{
    list<string> filename;
    fs::path directoryPath = directories[pos]; 
    if (!fs::is_directory(directoryPath)) {
        std::cerr << "The provided path is not a directory." << std::endl;
    }

    // 遍历目录下的所有文件
    try {
        for (const auto& entry : fs::directory_iterator(directoryPath)) {
            // 打印文件的路径
            string line = entry.path().string();
            if( line.find("gene") != std::string::npos ){
                filename.push_back(line);
            }
        }
    } catch (const fs::filesystem_error& e) {
        std::cerr << "An error occurred: " << e.what() << std::endl;
    }
    for(auto & u : filename){
        ifstream file(u);
        string line;
        while(getline(file,line)){
            istringstream iss(line);
            int pos;
            while(iss >> pos){
                vec[pos] ++;
            }
        }
        file.close();
    }

}

void writeData(vector<double> & genemat,int pos)
{
    string directoryPath = directories[pos].string(); 
    directoryPath = directoryPath + "/result.txt";
    ofstream file(directoryPath);
    if (!file.is_open()) {
        std::cerr << "Unable to open file." << std::endl;
    }
     struct ps
    {
        int pos;
        int freq;
    };
    
    std::vector<ps> vecs(genemat.size());
    for(int i = 0;i < genemat.size();i++)
    {
        vecs[i].pos = i+1;
        vecs[i].freq = genemat[i];
    }

    std::sort(vecs.begin(),vecs.end(),[](ps p1, ps p2){ return(p1.freq > p2.freq); });
    int count = 0;
    for(auto & p :vecs)
    {
        file << p.pos <<" " << p.freq << endl;
        count ++;
        if(count >= 3001){
            break;
        }
    }
    file.close();
}
void show(const vector<double> & genemat,int chunk=100)
{
    struct ps
    {
        int pos;
        int freq;
    };
    
    std::vector<ps> vecs(genemat.size());
    for(int i = 0;i < genemat.size();i++)
    {
        vecs[i].pos = i+1;
        vecs[i].freq = genemat[i];
    }

    std::sort(vecs.begin(),vecs.end(),[](ps p1, ps p2){ return(p1.freq > p2.freq); });
    int count = 0;
    for(auto & p :vecs)
    {
        cout << p.pos <<" " << p.freq << endl;
        count ++;
        if(count >= chunk){
            break;
        }
    }
}
int main()
{
    for(int i = 0;i < directories.size();i++){
        vector<double> genemat(3000,0);

        readFile(genemat,i);
        show(genemat);
        writeData(genemat,i);
    }
}